package com.zhenyi.jiahua.index;

import java.io.File;

import com.cenjiawen.common.IndexController;
import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.utils.PathUtils;
import com.utils.image.UploadUtils;
import com.zhenyi.boya.interceptor.AuthInterceptor;

import cn.hutool.core.io.FileUtil;

@Before(AuthInterceptor.class)
public class ApiController extends IndexController {

	public void uploadFile() {
		// String path
		File file = getFileParam("file");
		File path = new File(PathUtils.getFile("jh", "attachement", file.getName()));
		FileUtil.move(file, path, true);
		StringBuilder sb = new StringBuilder();
		sb.append("/jh/api/file?name=").append(file.getName());

		renderResult(sb.toString());
	}

	public void file() {
		String name = getPara("name");
		if (StrKit.isBlank(name)) {
			renderFailure();
			return;
		}
		// File file = new File(PathKit.getWebRootPath() + File.separatorChar +
		// "upload" + File.separatorChar + name);
		File file = new File(PathUtils.getFile("jh", "attachement", name));
		if (!file.exists()) {
			renderFailure(404, "not found");
			return;
		}
		renderFile(file);
	}

	public void uploadImage() {
		File file = getFileParam("file");
		String name = file.getName();
		String url = UploadUtils.upload(file);
		DBMap map = new DBMap();
		map.put("name", name);
		map.put("url", url);
		renderSuccess(map);
	}

}
